<?php
include ("../_vars.php");

echo "Hello admin!";

error_reporting(0);

//$n_rows = 0;

function echotd($string) {
  echo "<td>$string<td/>";
}

function echoTableHeader(){
  echo "<tr>";
  echotd("Active");
  echotd("Id");
  echotd("Name");
  echotd("Div");
  echotd("Active");
  echo "<tr/>";
}

function fetchProviders() {
  global $n_rows; 
  global $result_array;
  
  $result_array=array();
  
  $res = mysql_query("SELECT * FROM `adds` ORDER BY `active` DESC , `id` DESC");
  // O
  echo mysql_error();

  $i=0;
  while ($row = mysql_fetch_assoc($res) ) {
    $result_array[$i] = array( "id" => $row["id"], "active" => $row["active"], "name" =>$row["name"], "div"=>$row["div"]);
    $i++;
  }
  $n_rows = $i;
}

function showProviders() {
  global $n_rows; 
  global $result_array;
  echo "<hr/>";
  echo "<h3>Existing providers</h3>";
  echo "<form id='admin-add-form' method='post' >";
  echo "<table>";
  echoTableHeader();
  
  for ($i=0;$i<$n_rows;$i++) {
    echo "<tr>";
    $id = $result_array[$i]["id"];
    $name = $result_array[$i]["name"]; 
    $div = $result_array[$i]["div"];
    $active = $result_array[$i]["active"];
    $value = "checked='checked'";
    if ( $active == 0 )
      $value = "";
    echotd("<input type='checkbox' name=\"provider-$i\" $value>");
    echotd($id);
    echotd($name);
    echotd($div);
    $is_active = "No";
    if ($active == 1)
      $is_active = "Yes";
    echotd($is_active);
    echo "<tr/>";
  }

  echo "<table/>";  
  echo "<input type='submit' value='Update' >";
  echo "<input type='hidden' name='toggle' value='1' >";
  echo "<form/>";
  echo "<br/>";

}

function addProvider($name, $div) {
  mysql_query("INSERT INTO `adds` ( `id`, `name` , `div` ) VALUES ( NULL, '$name', '$div') ");
  
  echo mysql_error();
}

function showInsertForm(){
?>
<hr/>
<h3>Add new provider</h3>
<form id="admin-insert-form" method="post">

 Provider name: <br/>
 <input type="text" name="provider-name" /><br/>
 Provider div<br/>
 <textarea width="40" height="50" name="provider-div" ></textarea> <br/>
 <input type="hidden" name="insert" value="1"/>
 <input type="submit" name="Submit" value="Add provider" />

</form>
<?

}

fetchProviders();

if ($_POST["insert"] == 1) {
  $name = $_POST["provider-name"];
  $div = $_POST["provider-div"];
  if ($name != "")
    addProvider( $name , $div);
  header("Location: /lt320/admin/");
}

if ($_POST["toggle"] == 1) {

  for ($i=0;$i<$n_rows;$i++) {

   $bit = 0;
   if ( $_POST["provider-$i"] )
    $bit = 1;
   
   $id = $result_array[$i]["id"];
   mysql_query("UPDATE `adds` SET `active` =$bit WHERE `id` =$id ");
  }
  
  header("Location: /lt320/admin/");
}

showProviders();
showInsertForm();

?>
<hr/>
Usage reports are <a href="report.php" >here</a>
